package cn.wolfcode.luowowo.member.service.impl;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AssertUtil;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements IUserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    public UserInfo get(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    public Boolean checkPhone(String phone) {
        //AssertUtil.checkPhone(phone,"手机号应为11位数");
        int count = userInfoMapper.selectCheckByPhone(phone);
        return count > 0;
    }

    public void sendVerifyCode(String phone) {
        //生成验证码
        String code = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);
        //发短信
        StringBuilder sb = new StringBuilder();
        sb.append("您的验证码是:").append(code).append("请在" + Consts.VERIFY_CODE_VAI_TIME + "分钟内使用");
        System.out.println(sb);
        //将验证码存在redis中去 把电话号码当前唯一的传过去
        userInfoRedisService.setVerifyCode(phone, code);
    }

    public void userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) throws LogicException {
        //判断参数是否为空
        AssertUtil.hasLength(phone, "手机号码不能为空");
        AssertUtil.hasLength(nickname, "用户名不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "确认密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");
        //判断二次输入密码是否一致
        AssertUtil.hasEquals(password, rpassword, "两次密码不一致");
        //判断手机号码是否唯一
        AssertUtil.checkPhone(phone);

        if (this.checkPhone(phone)) {
            throw new LogicException("手机号码已经被注册了");
        }
        //判断验证码是否正确,是否过期
        String code = userInfoRedisService.getVerifyCode(phone);
        if(code==null|| !verifyCode.equalsIgnoreCase(code)){
            throw new LogicException("验证码过期或者错误");
        }
        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(phone);
        userInfo.setNickname(nickname);
        userInfo.setLevel(1);
        userInfo.setPassword(password);
        userInfo.setState(UserInfo.STATE_DISABLE);//正常状态
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfoMapper.insert(userInfo);
    }

    public String userLogin(String username, String password) throws LogicException{
        AssertUtil.hasLength(username, "用户名不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        //检查账号密码是否存在
        UserInfo user=userInfoMapper.selectUserByUsernameAndPasssword(username,password);
        if(user==null){
            throw new LogicException("用户不存在");
        }
        //那么就创建token,把token作为key,user作为value放到redis中
        String token= UUID.randomUUID().toString().replaceAll("-","");
        userInfoRedisService.setToken(token,user);
        return token;
    }

    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }

    //获得关注的对象集合 在数据库中存的是逗号分隔的用户id字符串
    @Override
    public List<UserInfo> listByFollow(Long id) {
        //先查出关注的用户id集合字符串
        String idStrs = userInfoMapper.selectByFollow(id);
        List<UserInfo> list = new ArrayList<>();
        //再分隔字符串,遍历查询出8个用户
        if(StringUtils.isNotBlank(idStrs)){
            Long[] ids = this.getRefIds(idStrs);
            //根据id结合查询用户集合
            list = userInfoMapper.selectByIds(ids);
        }
        return list;
    }

    //根据用户id查询出用户的粉丝集合  数量多要分页  日后再研究
    @Override
    public List<UserInfo> listByFans(Long id) {
        List<UserInfo> list = new ArrayList<>();
        //查询出粉丝的用户id集合字符串 逗号分隔的
        String idStrs = userInfoMapper.selectFansByUserID(id);
        //切割字符串 获得数组 再遍历查询用户获得集合
        Long[] ids = this.getRefIds(idStrs);
        //注意到有人没有粉丝的   因为sql是用遍历数组操作  空数组会报错
        if(ids==null){
            return null;
        }
        list = userInfoMapper.selectByIds(ids);
        return list;
    }

    @Override
    public void updateHeadImgById(String fileName, Long id) {
        userInfoMapper.updateHeadImgById(fileName,id);
    }

    @Override
    public void updateSettingUserInfo(UserInfo updateUser) {
        userInfoMapper.updateSettingUserInfo(updateUser);
    }

    @Override
    public UserInfo getByUserId(Long id) {
        return userInfoMapper.getByUserId(id);
    }

    @Override
    public long getFansCount(Long id) {
        String s = userInfoMapper.getFansCount(id);
        int count = 0;

        if(s == null){
            return 0;
        }else{
            for(int i = 0;i<s.length()-1;i++){

                count++;
            }
        }
        count = count/2 +1;
        return count;
    }

    @Override
    public boolean fans(Long cid, Long id) {

        //先查出这个cid的粉丝
        String fans = userInfoMapper.getFansCount(cid);

        //判断里面是否存在id
        if(fans == null){
            //增加一个粉丝
            String s = String.valueOf(id);
            userInfoMapper.saveFans(cid,s);
        }else{
            //先判定存入的粉丝是否已经存在
            String[] fs = fans.split(",");
            String s = String.valueOf(id);
            for (String f : fs) {
                //已经存在,返回false
                if(f.equals(s)){
                    return false;
                }
            }

            //不存在,在关注的中间表,给cid 加上,id
            StringBuilder sb = new StringBuilder();
            sb.append(fans).append(",").append(s);
            userInfoMapper.updateFans(cid,sb.toString());
        }
        //新增成功,返回true
        return true;
    }

    @Override
    public void updatePhoneById(String phone, Long id) {
        userInfoMapper.updatePhoneById(phone,id);
    }

    @Override
    public Boolean checkPhoneById(String phone, Long id) {

        int count =  userInfoMapper.checkPhoneById(phone,id);
        return count>0;
    }

    public Long[] getRefIds(String idStrs){
        Long[] ids = null;
        if(StringUtils.isNotBlank(idStrs)){
            String[] strs = idStrs.split(",");
            ids = new Long[strs.length];
            //如果用户关注对象大于8个  只取8个用户
            if(strs.length>8){
                for (int i = 0; i <8 ; i++) {
                    ids[i] =  Long.parseLong(strs[i]);
                }
            }else{
                for (int i = 0; i <strs.length ; i++) {
                    ids[i] =  Long.parseLong(strs[i]);
                }
            }
        }
        return ids;
    }

}
